import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AuthService } from '@auth/index';
import { FriendEntity } from '@modules/friend/entity/friend.entity';
import { UserDto, UserRegisterDto, UserLoginDto } from './dto/index';
import { UserEntity } from './entity/user.entity';

export type User = any;

@Injectable()
export class UserService {
  constructor(
    private tokenService: AuthService,
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    @InjectRepository(FriendEntity)
    private readonly friendRepository: Repository<FriendEntity>,
  ) {}

  async login(userLogin: UserLoginDto): Promise<any> {
    const { email } = userLogin;
    if (!email || !userLogin.password) return { code: 500, msg: '请输入账号密码' };

    const isUser = await this.userRepository.findOne({ where: { email } });
    if (!isUser) return { code: 500, msg: '用户不存在' };

    const result = await this.userRepository.findOne({ where: [{ email, password: userLogin.password }] });
    if (!result) return { code: 500, msg: '账户或密码不正确' };

    const { password, ...arg } = result;
    const payload = { userId: result.userId, username: result.username, email: result.email };
    return { code: 200, msg: '登陆成功', data: { user: arg, token: this.tokenService.generateToken(payload, '1d') } };
  }

  async register(userRegister: UserRegisterDto): Promise<any> {
    const isHave = await this.userRepository.findOne({ where: { email: userRegister.email } });
    if (isHave) return { code: 500, msg: '用户已存在' };

    const params: UserDto = { ...userRegister, account: 'dsf', imgUrl: 'http://localhost:7001/images/download.png' };
    await this.userRepository.save(params);
    return { msg: '注册成功', code: 200 };
  }

  async findOne(username: string) {
    const result = await this.userRepository.findOne({ where: { username } });
    return result;
  }

  async getUser(token: string) {
    const result = await this.tokenService.getTokenUser(token);
    try {
      if (result.userId) {
        const { password, ...arg } = await this.userRepository.findOne({ where: { userId: result.userId } });
        return { code: 200, msg: '获取用户成功', data: arg };
      }
    } catch (e) {
      return { code: 500, msg: '获取用户失败', data: e };
    }
  }

  /**
   * 获取用户信息列表
   */
  async getUserList(token: string) {
    const { userId } = await this.tokenService.getTokenUser(token);

    if (userId) {
      const userResult = await this.userRepository.find({
        select: [
          'userId',
          'username',
          'account',
          'email',
          'sex',
          'birth',
          'phone',
          'desc',
          'imgUrl',
          'createTime',
          'updateTime',
        ],
        order: {
          userId: 'DESC',
        },
      });
      const friendData = await this.friendRepository.find({ where: [{ userId }, { friendId: userId }] });
      const ids = friendData.map((item) => {
        if (item.friendId === userId) {
          return Number(item.userId);
        }
        return Number(item.friendId);
      });
      const formatUser = userResult.map((item) => {
        const idsRes = ids.find((value: number) => value === Number(item.userId));
        // status: 0: 不是好友 1:好友 2 代表自己
        if (idsRes && idsRes === Number(item.userId)) {
          item.status = 1;
        } else if (item.userId === userId) {
          item.status = 2;
        } else {
          item.status = 0;
        }
        return item;
      });
      return { code: 200, msg: '获取成功', data: formatUser };
    }
    return { code: 500, msg: '获取失败' };
  }

  /**
   * 修改用户信息
   */
  async updateUser(token: string, userBody: UserDto) {
    const tokenResult = await this.tokenService.getTokenUser(token);
    const userResult = await this.userRepository.findOne({ where: { userId: tokenResult.userId } });
    await this.userRepository
      .createQueryBuilder()
      .update()
      .set({
        username: userBody.username || userResult.username,
        account: userBody.account || userResult.account,
        email: userBody.email || userResult.email,
        sex: userBody.sex || userResult.sex,
        birth: userBody.birth || userResult.birth,
        phone: userBody.phone || userResult.phone,
        desc: userBody.desc || userResult.desc,
        imgUrl: userBody.imgUrl || userResult.imgUrl,
      })
      .where({ userId: tokenResult.userId })
      .execute();
    return { code: 200, msg: '修改成功' };
  }

  /**
   * 修改密码
   */
  async updatePassword(token: string, userBody: UserDto) {
    const tokenResult = await this.tokenService.getTokenUser(token);
    const userResult = await this.userRepository.findOne({ where: { userId: tokenResult.userId } });
    if (userResult.password === userBody.password) {
      const newPassword = '222222';
      await this.userRepository
        .createQueryBuilder()
        .update()
        .set({
          password: newPassword,
        })
        .where({
          userId: tokenResult.userId,
        });
      return { code: 200, msg: '密码修改成功' };
    }
    return { code: 500, msg: '密码修改失败' };
  }

  /**
   * 重置密码
   */
  async resetPassword({ email, password, newPassword }) {
    const userResult = await this.userRepository.findOne({ where: { email } });
    if (userResult.password === password) {
      await this.userRepository
        .createQueryBuilder()
        .update()
        .set({
          password: newPassword,
        })
        .where({ email });
      return { code: 200, msg: '重置密码成功' };
    }
    return { code: 500, msg: '重置密码失败' };
  }
}
